package com.icongyou.enterprise.course_detail.service.impl;

import com.icongyou.enterprise.course_detail.entity.AssignmentEntity;
import com.icongyou.enterprise.course_detail.entity.AssignmentRankEntity;
import com.icongyou.enterprise.course_detail.entity.vo.AssignmentCardVO;
import com.icongyou.enterprise.course_detail.entity.vo.CoreAchievementVO;
import com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO;
import com.icongyou.enterprise.course_detail.entity.vo.RankTrendPointVO;
import com.icongyou.enterprise.course_detail.entity.vo.TeamContributionVO;
import com.icongyou.enterprise.course_detail.mapper.CourseDetailMapper;
import com.icongyou.enterprise.course_detail.service.CourseDetailService;
import com.icongyou.enterprise.data_aggregation.entity.*;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_marking.service.HighPotentialSubmissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 

/**
 * 课程详情服务实现
 */
@Slf4j
@Service
public class CourseDetailServiceImpl implements CourseDetailService {

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private DataAggregationService dataAggregationService;
    
    @Autowired
    private HighPotentialSubmissionService highPotentialSubmissionService;

    @Override
    public CourseDetailVO getCourseDetail(String studentId, String courseId) {
        CourseDetailVO courseDetailVO = new CourseDetailVO();

        // 1. 获取课程基本信息
        CourseEntity course = dataAggregationService.getCourseById(courseId);
        if (course != null) {
            courseDetailVO.setCourseId(course.getCourseId());
            courseDetailVO.setCourseName(course.getCourseName());
        }

        // 2. 获取学生基本信息
        UserEntity student = dataAggregationService.getStudentById(studentId);
        if (student != null) {
            courseDetailVO.setStudentId(student.getId());
            courseDetailVO.setStudentName(student.getRealName());
        }

        // 3. 获取学生课程进度（总分和排名）
        CourseProgressEntity progress = dataAggregationService.getStudentCourseProgress(studentId, courseId);
        if (progress != null) {
            courseDetailVO.setTotalScore(progress.getTotalScore() != null ? progress.getTotalScore().doubleValue() : 0.0);
            courseDetailVO.setCourseRank(progress.getRanking());
        }

        // 4. 预拉取：学生在该课程的 assignment_scores 与学生相关的提交（包含团队提交）
        List<AssignmentStudentEntity> assignmentScores = dataAggregationService.getStudentAssignmentScore(studentId, courseId);
        Map<String, java.math.BigDecimal> assignedScoreMap = new HashMap<>();
        if (assignmentScores != null) {
            for (AssignmentStudentEntity ase : assignmentScores) {
                if (ase.getAssignmentId() != null && ase.getAssignedScore() != null) {
                    assignedScoreMap.put(ase.getAssignmentId(), ase.getAssignedScore());
                }
            }
        }

        List<SubmissionEntity> studentRelatedSubmissions = dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId);
        Map<String, List<SubmissionEntity>> submissionsByAssignment = new HashMap<>();
        if (studentRelatedSubmissions != null) {
            for (SubmissionEntity sub : studentRelatedSubmissions) {
                submissionsByAssignment.computeIfAbsent(sub.getAssignmentId(), k -> new ArrayList<>()).add(sub);
            }
        }

        // 5. 获取学生在该课程的所有任务（包含团队任务）
        List<AssignmentEntity> assignments = courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId);

        // 6. 为每个任务构建详细信息
        List<AssignmentCardVO> assignmentCards = new ArrayList<>();
        for (AssignmentEntity assignment : assignments) {
            AssignmentCardVO cardVO = buildAssignmentCard(assignment, studentId, assignedScoreMap, submissionsByAssignment);
            assignmentCards.add(cardVO);
        }

        courseDetailVO.setAssignments(assignmentCards);

        // 7. 构建任务排名变化趋势数据
        List<RankTrendPointVO> rankTrend = buildRankTrend(assignments, assignmentCards);
        courseDetailVO.setRankTrend(rankTrend);

        // 8. 计算团队贡献度统计
        TeamContributionVO teamContribution = calculateTeamContribution(assignmentCards, submissionsByAssignment, studentId);
        courseDetailVO.setTeamContribution(teamContribution);

        return courseDetailVO;
    }

    /**
     * 构建任务卡片
     */
    private AssignmentCardVO buildAssignmentCard(AssignmentEntity assignment, String studentId, Map<String, java.math.BigDecimal> assignedScoreMap,
                                                 Map<String, List<SubmissionEntity>> submissionsByAssignment) {
        AssignmentCardVO cardVO = new AssignmentCardVO();
        
        // 基本信息
        cardVO.setAssignmentId(assignment.getAssignmentId());
        cardVO.setAssignmentName(assignment.getAssignmentName());
        cardVO.setAssignmentType(assignment.getAssignmentType());
        cardVO.setDescription(assignment.getDescription());
        cardVO.setStartTime(assignment.getStartTime());

        // 获取学生的相关提交记录（包含团队提交）
        List<SubmissionEntity> submissions = submissionsByAssignment.getOrDefault(assignment.getAssignmentId(), new ArrayList<>());

        // 选择与该学生相关且最新的一条提交：
        // - 对个人任务，submission.studentId == studentId
        // - 对团队任务，submission.contributionRate 包含 studentId
        SubmissionEntity selected = submissions.stream()
                .filter(s -> {
                    if (s == null) return false;
                    if (studentId.equals(s.getStudentId())) return true;
                    if (s.getContributionRate() != null) {
                        return s.getContributionRate().stream().anyMatch(it -> studentId.equals(it.getStudentId()));
                    }
                    return false;
                })
                .sorted((a, b) -> {
                    if (a.getSubmissionTime() == null && b.getSubmissionTime() == null) return 0;
                    if (a.getSubmissionTime() == null) return 1;
                    if (b.getSubmissionTime() == null) return -1;
                    return b.getSubmissionTime().compareTo(a.getSubmissionTime()); // 最新优先
                })
                .findFirst().orElse(null);

        if (selected != null) {
            // 提交时间和是否逾期
            cardVO.setSubmissionTime(selected.getSubmissionTime());
            cardVO.setIsLate(selected.getIsLate() != null && selected.getIsLate() == 1);


            // 获取贡献度（传入任务类型）
            java.math.BigDecimal contributionRate = getStudentContributionRate(selected, studentId, assignment.getAssignmentType());
            cardVO.setContributionRate(contributionRate);
            

            // 获取教师评语和成绩
            List<GradeEntity> grades = dataAggregationService.getStudentGrade(selected.getSubmissionId());
            if (grades != null && !grades.isEmpty()) {
                GradeEntity grade = grades.get(0);
                cardVO.setTeacherComment(grade.getTextComment());

                // 根据贡献度计算实际得分
                if (grade.getFinalScore() != null && contributionRate != null) {
                    java.math.BigDecimal actualScore = grade.getFinalScore()
                            .multiply(contributionRate)
                            .divide(new java.math.BigDecimal("100"), 2, java.math.RoundingMode.HALF_UP);
                    cardVO.setScore(actualScore);
                } else {
                    cardVO.setScore(grade.getFinalScore());
                }
            } else {
                // 若没有批改信息，尝试使用 assignment_students 中的 assignedScore
                java.math.BigDecimal assigned = assignedScoreMap.get(assignment.getAssignmentId());
                if (assigned != null && contributionRate != null) {
                    java.math.BigDecimal actualScore = assigned.multiply(contributionRate).divide(new java.math.BigDecimal("100"), 2, java.math.RoundingMode.HALF_UP);
                    cardVO.setScore(actualScore);
                } else if (assigned != null) {
                    cardVO.setScore(assigned);
                }
            }

            // 获取核心成果
            List<CoreAchievementVO> coreAchievements = buildCoreAchievements(selected, grades, studentId);
            cardVO.setCoreAchievements(coreAchievements);
        } else {
            // 无提交：若 assignment_students 中存在 assignedScore，则显示之
            java.math.BigDecimal assigned = assignedScoreMap.get(assignment.getAssignmentId());
            if (assigned != null) {
                cardVO.setScore(assigned);
            }
        }

        // 获取任务排名
        AssignmentRankEntity rankEntity = courseDetailMapper.getStudentAssignmentRank(
                assignment.getAssignmentId(), studentId);
        if (rankEntity != null) {
            cardVO.setAssignmentRank(rankEntity.getRank());
        }

        return cardVO;
    }

    /**
     * 获取学生在提交中的贡献度
     * @param submission 提交记录
     * @param studentId 学生ID
     * @param assignmentType 任务类型（0=个人，1=团队）
     * @return 贡献度百分比
     */
    private BigDecimal getStudentContributionRate(SubmissionEntity submission, String studentId, Integer assignmentType) {
        
        if (submission.getContributionRate() == null || submission.getContributionRate().isEmpty()) {
            
            // 如果没有贡献度信息
            if (assignmentType != null && assignmentType == 0) {
                // 个人任务：默认100%
                return new BigDecimal("100");
            } else {
                // 团队任务：没有贡献度信息视为0（数据异常）
                return new BigDecimal("0");
            }
        }

        
        // 从贡献度列表中查找该学生的贡献度
        for (SubmissionEntity.ContributionItem item : submission.getContributionRate()) {
            if (item.getStudentId().equals(studentId)) {
                return item.getRate();
            }
        }

        
        // 在贡献度列表中没有找到该学生：
        // - 个人任务：异常情况，返回100
        // - 团队任务：该学生不在团队中，返回0
        if (assignmentType != null && assignmentType == 0) {
            return new BigDecimal("100");
        } else {
            return new BigDecimal("0");
        }
    }

    /**
     * 构建核心成果列表
     */

    /**
     * 构建核心成果列表
     */
    private List<CoreAchievementVO> buildCoreAchievements(SubmissionEntity submission, List<GradeEntity> grades, String studentId) {
        List<CoreAchievementVO> achievements = new ArrayList<>();
        
        CoreAchievementVO achievement = new CoreAchievementVO();
        achievement.setSubmissionId(submission.getSubmissionId());
        achievement.setContentUrl(submission.getContentUrl());
        achievement.setDescription("作品内容");
        achievement.setLikeCount(submission.getLikeCount() != null ? submission.getLikeCount() : 0);
        achievement.setFavoriteCount(submission.getFavoriteCount() != null ? submission.getFavoriteCount() : 0);
        
        // 判断是否为高潜力成果（查询high_potential_submissions表）
        boolean isHighPotential = highPotentialSubmissionService.isSubmissionMarked(studentId, submission.getSubmissionId());
        achievement.setIsHighPotential(isHighPotential);
        
        achievements.add(achievement);
        
        return achievements;
    }

    /**
     * 构建任务排名变化趋势数据
     */
    private List<RankTrendPointVO> buildRankTrend(List<AssignmentEntity> assignments, List<AssignmentCardVO> assignmentCards) {
        List<RankTrendPointVO> trendPoints = new ArrayList<>();
        
        // 为每个任务创建一个趋势数据点
        for (int i = 0; i < assignments.size() && i < assignmentCards.size(); i++) {
            AssignmentEntity assignment = assignments.get(i);
            AssignmentCardVO card = assignmentCards.get(i);
            
            // 只有有排名的任务才加入趋势
            if (card.getAssignmentRank() != null) {
                RankTrendPointVO point = new RankTrendPointVO();
                point.setAssignmentId(assignment.getAssignmentId());
                point.setAssignmentName(assignment.getAssignmentName());
                point.setStartTime(assignment.getStartTime());
                point.setRank(card.getAssignmentRank());
                
                // 获取该任务的总参与人数（通过查询排名列表）
                List<AssignmentRankEntity> rankings = courseDetailMapper.getAssignmentRankings(assignment.getAssignmentId());
                point.setTotalParticipants(rankings != null ? rankings.size() : 0);
                
                trendPoints.add(point);
            }
        }
        
        return trendPoints;
    }

    /**
     * 计算团队贡献度统计
     */
    private TeamContributionVO calculateTeamContribution(List<AssignmentCardVO> assignmentCards, 
                                                         Map<String, List<SubmissionEntity>> submissionsByAssignment,
                                                         String currentStudentId) {
        TeamContributionVO contribution = new TeamContributionVO();
        
        BigDecimal teamContributionSum = BigDecimal.ZERO;
        int teamTaskCount = 0;
        
        // 用于收集所有团队成员的贡献度（studentId -> 贡献度总和）
        Map<String, BigDecimal> memberContributionMap = new HashMap<>();
        Map<String, Integer> memberTaskCountMap = new HashMap<>();
        
        
        // 只统计团队任务
        for (AssignmentCardVO card : assignmentCards) {
            
            // assignmentType: 0=个人，1=团队
            if (card.getAssignmentType() != null && card.getAssignmentType() == 1) {
                // 团队任务：累加当前学生在团队中的贡献度
                if (card.getContributionRate() != null) {
                    teamContributionSum = teamContributionSum.add(card.getContributionRate());
                    teamTaskCount++;
                    
                    
                    // 收集该任务中所有团队成员的贡献度
                    List<SubmissionEntity> submissions = submissionsByAssignment.get(card.getAssignmentId());
                    if (submissions != null && !submissions.isEmpty()) {
                        for (SubmissionEntity submission : submissions) {
                            if (submission.getContributionRate() != null) {
                                for (SubmissionEntity.ContributionItem item : submission.getContributionRate()) {
                                    String memberId = item.getStudentId();
                                    BigDecimal rate = item.getRate();
                                    
                                    memberContributionMap.put(memberId, 
                                        memberContributionMap.getOrDefault(memberId, BigDecimal.ZERO).add(rate));
                                    memberTaskCountMap.put(memberId, 
                                        memberTaskCountMap.getOrDefault(memberId, 0) + 1);
                                }
                            }
                        }
                    }
                } else {
                }
            } else if (card.getAssignmentType() != null && card.getAssignmentType() == 0) {
            }
        }
        
        // 计算当前学生的平均贡献度
        BigDecimal averageContribution = BigDecimal.ZERO;
        if (teamTaskCount > 0) {
            averageContribution = teamContributionSum.divide(
                new BigDecimal(teamTaskCount), 2, RoundingMode.HALF_UP
            );
        }
        
        // 构建团队成员贡献度列表
        List<TeamContributionVO.MemberContribution> memberContributions = new ArrayList<>();
        for (Map.Entry<String, BigDecimal> entry : memberContributionMap.entrySet()) {
            String memberId = entry.getKey();
            BigDecimal totalContrib = entry.getValue();
            Integer taskCount = memberTaskCountMap.get(memberId);
            
            BigDecimal avgContrib = taskCount > 0 ? 
                totalContrib.divide(new BigDecimal(taskCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
            
            TeamContributionVO.MemberContribution memberContrib = new TeamContributionVO.MemberContribution();
            memberContrib.setStudentId(memberId);
            memberContrib.setAvgContribution(avgContrib);
            memberContrib.setIsCurrentStudent(memberId.equals(currentStudentId));
            
            // 获取学生姓名
            UserEntity student = dataAggregationService.getStudentById(memberId);
            if (student != null) {
                memberContrib.setStudentName(student.getRealName());
            } else {
                memberContrib.setStudentName("未知");
            }
            
            memberContributions.add(memberContrib);
            
        }
        
        // 按贡献度降序排序
        memberContributions.sort((a, b) -> b.getAvgContribution().compareTo(a.getAvgContribution()));
        
        
        contribution.setTeamContribution(averageContribution);
        contribution.setTotalContribution(averageContribution);
        contribution.setTeamTaskCount(teamTaskCount);
        contribution.setMemberContributions(memberContributions);
        
        // 百分比设置为100%（因为只统计团队任务）
        contribution.setPersonalPercentage(BigDecimal.ZERO);
        contribution.setTeamPercentage(new BigDecimal("100.00"));
        
        return contribution;
    }
}
